package br.ufrgs.inf.sissw.app;

import java.util.ArrayList;

import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import br.ufrgs.inf.sissw.app.helpers.RuMenuHelper;

public class RuActivity extends AbstractDashboardActivity {

	private ArrayList<ArrayList<String>> menu;
	private LinearLayout monday, tuesday, wednesday, thursday, friday;
	private HorizontalScrollView scrollView;
	private PopupWindow pw;
	private boolean isThreadFinished = false;
	private boolean hasData = false;

	@Override
	protected int getContentView() {
		return R.layout.ru_activity;
	}

	@Override
	protected int getFeatureNameResourceId() {
		return R.string.ru;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		try {
			if (hasData) {

			} else {
				if (!isOnline()) {
					Toast.makeText(
							getApplicationContext(),
							"Não foi possível baixar os dados. Verifique se há conexão.",
							Toast.LENGTH_LONG).show();
				} else {
					new Thread(new Runnable() {
						public void run() {
							try {

								runOnUiThread(new Runnable() {
									public void run() {
										showPopup();
									}
								});
								fetchMenu();

								if (menu != null && menu.size() == 5) {
									hasData = true;
									runOnUiThread(new Runnable() {
										public void run() {
											populateDays();
										}
									});

								}

								runOnUiThread(new Runnable() {
									public void run() {
										pw.dismiss();
									}
								});

							} catch (Exception e) {
								e.printStackTrace();
							} finally {
								isThreadFinished = true;
							}
						}
					}).start();
				}

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	private void fetchMenu() {
		try {
			menu = RuMenuHelper.fetchWeekData();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void populateDays() {

		ArrayList<LinearLayout> days = new ArrayList<LinearLayout>();
		monday = (LinearLayout) findViewById(R.id.mondayWidget);
		days.add(monday);
		tuesday = (LinearLayout) findViewById(R.id.tuesdayWidget);
		days.add(tuesday);
		wednesday = (LinearLayout) findViewById(R.id.wednesdayWidget);
		days.add(wednesday);
		thursday = (LinearLayout) findViewById(R.id.thursdayWidget);
		days.add(thursday);
		friday = (LinearLayout) findViewById(R.id.fridayWidget);
		days.add(friday);

		for (int i = 0; i < 5; i++) {
			for (String item : menu.get(i)) {
				TextView newItem = (TextView) TextView.inflate(this,
						R.layout.menu_item, null);
				newItem.setText(item);
				days.get(i).addView(newItem);
			}
		}
	}

	// A lógica utilizada returna TRUE quando há conexão, mas gera exceção caso
	// contrário. Por isso
	// a captura de exceção sem nenhum tratamento especial.
	private boolean isOnline() {
		boolean ret = false;
		try {
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			ret = cm.getActiveNetworkInfo().isConnectedOrConnecting();
		} catch (Exception e) {

		}

		return ret;
	}

	private void showPopup() {

		try {
			// We need to get the instance of the LayoutInflater, use the
			// context of this activity
			LayoutInflater inflater = (LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			// Inflate the view from a predefined XML layout
			View layout = inflater.inflate(R.layout.loading_popup,
					(ViewGroup) findViewById(R.id.popup_element));
			// create a 300px width and 470px height PopupWindow
			pw = new PopupWindow(layout, 260, 140, true);
			// display the popup in the center
			pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
